<?php

class SearchEngine
{
    public static function Search( $searchExpression, $page, $pageLimit )
    {
        $result = Core::DBConn()->Query( 
            "
            SELECT id_page, content, page_title
            FROM page_content
            WHERE (POSITION(#searchText# IN page_title) <> 0) 
               OR (POSITION(#searchText# IN content) <> 0)
            LIMIT #start#, #count#
            ",
            array( 
                "#searchText#" => Util::Quote($searchExpression),
                "#start#" => max(0, ($page - 1) * $pageLimit),
                "#count#" => max(1, $pageLimit)
            )
        );
        return $result->GetAllAssoc();
    }

    public static function UpdateDatabase()
    {
        Core::DBConn()->Query( "TRUNCATE page_content" );

        $pages = Core::ResourceManager()->GetSearchPages();
        foreach ( $pages as $pageId)
        {
            $pageInfo = Pages::GetPageInfo($pageId);
            $pageUrl = SITE_URL . $pageInfo->path;
            echo $pageUrl . "<br>";

            Core::DBConn()->Query(
                "
                INSERT INTO page_content
                  SET
                    id_page = #id_page#,
                    content = #content#,
                    page_title = #page_title#
                ",
                Util::QuoteArray( array(
                    "#id_page#" => $pageInfo->id,
                    "#content#" => self::GetFileContent($pageUrl),
                    "#page_title#" => $pageInfo->title
                ) )
            );
        }
    }

    private static function GetFileContent($file)
    {
        $html = file_get_contents($file);

        $doc = @DOMDocument::loadHTML( $html );
        $xpathHelper = new XPathHelper( $doc );
        $nodes = $xpathHelper->GetNodes('/html/body//div[@class="content"]//text()[name(parent::node()) != "script" and name(parent::node()) != "style" and string-length(normalize-space(self::text())) > 1]');
        
        $texts = array();
        foreach ( $nodes as $node )
        {
            $text = $xpathHelper->Evaluate("normalize-space(self::text())", $node);
            if ( !($text[0] == '<' && preg_match("/<!--.*?-->/", $text)) )
            {
                $text = trim( preg_replace("/\W+/s", ' ', $text) );
                $texts[] = $text;
            }
        }

        $content = implode(" ", $texts);
        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        return $content;
    }
}

?>